/**
 * canvas 对象
 */
function createCanvas(width = 300, height = 150) {
  const canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  return canvas;
}

const random = Math.random;
const floor = Math.floor;

/**
 * 随机整数
 * @param {number} n
 * @returns [0, n)
 */
function intRand(n) {
  return floor(random() * n);
}

/**
 * 从范围[a, b)内随机
 * @param {number} a start
 * @param {number} b end
 * @returns [a, b)
 */
function rand(a, b) {
  if (b) {
    const diff = b - a;
    return a + intRand(diff);
  }
  return intRand(a);
}

/**
 * pick
 * @param {Array} arr array
 */
function pick(arr) {
  return arr[rand(arr.length)];
}

/**
 * 随机HEX颜色
 */
function hexColor() {
  return (
    "#" +
    Array(6)
      .fill(0)
      .map(() => rand(16).toString(16))
      .join("")
  );
}

/**
 * 随机RGB颜色
 */
function rgbColor() {
  return `rgb(${Array(3)
    .fill(0)
    .map(() => rand(256))
    .join(",")})`;
}

/**
 * 随机字母
 */
function alphabet() {
  const lower = rand(97, 122);
  const upper = rand(65, 90);
  return String.fromCharCode(pick([lower, upper]));
}

/**
 * 生成随机彩色图片URL
 */
function randImage(
  text,
  width = rand(50, 500),
  height = rand(50, 500),
  bgColor = hexColor(),
  fontColor = "white"
) {
  const canvas = createCanvas(width, height);
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = bgColor;
  ctx.fillRect(0, 0, width, height);

  ctx.fillStyle = fontColor;
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.font = Math.min(width, height) / 2 + "px bold";
  ctx.fillText(text, width / 2, height / 2);

  return canvas.toDataURL();
}

export { alphabet, hexColor, pick, rand, randImage, rgbColor };
